#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <cstring>
#include <string>
#include <unistd.h>

// ./client serverip serverport
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        return 1;
    }
    // socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "socket fail" << std::endl;
        return errno;
    }

    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];

    // connect
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;  
    server.sin_port = htons(serverport);
    // server.sin_addr.s_addr = inet_addr(serverip.c_str());
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);

    socklen_t len = sizeof(server);
    int n = connect(sockfd, (sockaddr*)&server, len);
    if(n < 0)
    {
        std::cerr << "connect fail" << std::endl;
        return errno;
    }

    // communication
    std::string buffer;
    while(true)
    {
        std::cout << "Please Enter# ";
        std::getline(std::cin, buffer);

        write(sockfd, buffer.c_str(), buffer.size());

        char inbuffer[4096];
        ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer)-1);
        if(n > 0)
        {
            inbuffer[n] = 0;
            std::cout << inbuffer << std::endl;
        }
    }













    return 0;
}